package cn.jlearn.proxy.agent.listener;

import cn.jlearn.proxy.agent.AgentStartApp;
import cn.jlearn.proxy.agent.container.ProxyClient;
import cn.jlearn.proxy.common.body.TcpTunnelBody;
import cn.jlearn.proxy.common.enums.MsgTypeEnum;
import cn.jlearn.proxy.common.enums.ProtocolEnum;
import cn.jlearn.proxy.common.packet.BsPacket;
import com.alibaba.fastjson.JSON;
import org.tio.client.intf.ClientAioListener;
import org.tio.core.ChannelContext;
import org.tio.core.Tio;
import org.tio.core.intf.Packet;

/**
 * @author qianyingchao
 * @version 1.0
 * @date 2021/5/10 6:13 下午
 */
public class ForwardClientListener implements ClientAioListener {

    @Override
    public void onAfterConnected(ChannelContext channelContext, boolean isConnected, boolean isReconnect) throws Exception {
    }

    @Override
    public void onAfterDecoded(ChannelContext channelContext, Packet packet, int packetSize) throws Exception {

    }

    @Override
    public void onAfterReceivedBytes(ChannelContext channelContext, int receivedBytes) throws Exception {

    }

    @Override
    public void onAfterSent(ChannelContext channelContext, Packet packet, boolean isSentSuccess) throws Exception {

    }

    @Override
    public void onAfterHandled(ChannelContext channelContext, Packet packet, long cost) throws Exception {

    }

    @Override
    public void onBeforeClose(ChannelContext channelContext, Throwable throwable, String remark, boolean isRemove) throws Exception {
        String bsId = (String) channelContext.get("bsId");

        TcpTunnelBody body = new TcpTunnelBody(bsId, ProtocolEnum.HTTP.getCode());
        BsPacket bsPacket = new BsPacket(MsgTypeEnum.TCP_TUNNEL_CLOSE_REQ.getCode(), JSON.toJSONBytes(body));

        Tio.sendToBsId(ProxyClient.clientTioConfig, AgentStartApp.TOKEN, bsPacket);
    }

}
